import React, { useState, useEffect } from 'react'
import Upload, { uploadFile } from '@components/Upload/Index'
import { awaitWrap } from '@js/tool'

function Main ({ value, onChange, config }) {
  const [maxLength, setMaxLength] = useState(undefined)
  const [accept, setAccept] = useState(undefined)
  const [readonly, setReadonly] = useState(undefined)
  useEffect(() => {
    if (config) {
      if (config.max !== undefined) {
        setMaxLength(config.max)
      }
      if (config.accept !== undefined) {
        setAccept(config.accept)
      }
      if (config.readonly !== undefined) {
        setReadonly(true)
      }
    }
  }, [config])
  return (
    <Upload value={value} onChange={onChange} maxLength={maxLength} accept={accept} readonly={readonly} />
  )
}

export async function formatValue (v) {
  if (v instanceof Array) {
    const [e, r] = await awaitWrap(uploadFile(v))
    if (e) {
      throw new Error(e.message)
    }
    if (r instanceof Array) {
      return r.map(li => li.id).join()
    }
  }
  return ''
}

export function formatInitValue (v, config = {}) {
  if (v instanceof Array) {
    return v.map(li => {
      li.name = li.filename
      return li
    })
  }
  return undefined
}

export default Main
